namespace math
{
    var baseItems = "0123456789ABCDEF";
    var baseNumber: { [id: string]: number } = (() =>
    {
        var obj = {};
        for (var i = 0, n = baseItems.length; i < n; i++)
        {
            obj[baseItems.charAt(i)] = i;
        }
        return obj;
    })();

    /**
     * 把基于base1的进制数字转换为基于base2的进制数字
     * @param numberstring 基于base1的进制数字
     * @param base1 进制值，2 <= base1 <= 16
     * @param base2 进制值，2 <= base2 <= 16
     */
    export function convertBase(numberstring: string, base1: number, base2: number)
    {
        var decimalism = baseToDecimalism(numberstring, base1);
        var base2String = decimalismToBase(decimalism, base2);
        return base2String;
    }

    /**
     * 把十进制数字转换为指定进制数字
     * @param decimalism 十进制数字
     * @param base 进制值，2 <= base <= 16
     */
    export function decimalismToBase(decimalism: number, base: number)
    {
        var value = "";
        while (decimalism > 0)
        {
            var remainder = decimalism % base;
            value = baseItems.charAt(remainder) + value;
            decimalism = ~~(decimalism / base);
        }
        return value;
    }

    /**
     * 把指定进制数字转换为十进制数字
     * @param numberstring 基于base的进制数字
     * @param base 进制值，2 <= base <= 16
     */
    export function baseToDecimalism(numberstring: string, base: number)
    {
        var value = 0;
        for (var i = numberstring.length - 1, baseN = 1; i >= 0; i-- , baseN *= base)
        {
            var c = numberstring.charAt(i)
            value += baseNumber[c] * baseN;
        }
        return value;
    }


}